import React, { useState, useEffect } from "react";
import { Tree, Spin, Input, Button, Space } from "antd";
import type { DataNode, TreeProps } from "antd/es/tree";
import { postWfs } from "@/services/os/api";
import { postCheckChooseFile } from "@/services/os/api";
import { useNavigate } from "react-router-dom";
import { message } from "antd";
// import {
//     FileOutlined,
//     FolderOutlined,
//     FolderOpenOutlined,
// } from "@ant-design/icons";
// import "./Wfs.css";

interface WfsProps {
    ifshow: boolean;
    changeShow: (show: boolean) => void;
    choosePath: (path: string) => string;
}

interface FileItem {
    type: "dir" | "file";
    size: string;
    time: number;
}

interface ApiResponse {
    message: Record<string, FileItem>;
    status_code: string;
    status: string;
}

const Wfs: React.FC<WfsProps> = ({ ifshow, changeShow, choosePath }) => {
    const navigate = useNavigate();
    const [treeData, setTreeData] = useState<DataNode[]>([]);
    const [loading, setLoading] = useState(false);
    const [selectedKeys, setSelectedKeys] = useState<React.Key[]>([]);
    const [expandedKeys, setExpandedKeys] = useState<React.Key[]>([]);
    const [loadedKeys, setLoadedKeys] = useState<Set<string>>(new Set());
    const [currentPath, setCurrentPath] = useState<string>("/");

    const fetchData = async (path: string = "/") => {
        setLoading(true);
        try {
            const res: ApiResponse = (await postWfs({
                path,
                method: "ls",
            }, '1')) || { message: {}, status_code: "", status: "" };

            return Object.entries(res.message).map(([key, value]) => ({
                title: (
                    <div className="tree-node-content">
                        <span className="node-name">{key}</span>
                        {/* {value.type === "file" && (
                            <span className="file-size">{value.size}</span>
                        )} */}
                    </div>
                ),
                key: path === "/" ? `/${key}` : `${path}/${key}`,
                isLeaf: value.type !== "dir",
                selectable: value.type !== "dir",
                className:
                    value.type === "dir" ? "directory-node" : "file-node",
                fileInfo: value,
            }));
        } catch (error) {
            console.error("Error fetching data:", error);
            return [];
        } finally {
            setLoading(false);
        }
    };

    const updateTreeData = (
        list: DataNode[],
        key: string,
        children: DataNode[],
    ): DataNode[] => {
        return list.map((node) => {
            if (node.key === key) return { ...node, children };
            return node.children
                ? {
                    ...node,
                    children: updateTreeData(node.children, key, children),
                }
                : node;
        });
    };

    const handleNodeInteraction = (node: DataNode) => {
        if (node.isLeaf) {
            setSelectedKeys([node.key]);
            setCurrentPath(node.key as string);
        } else {
            const newExpandedKeys = expandedKeys.includes(node.key)
                ? expandedKeys.filter((k) => k !== node.key)
                : [...expandedKeys, node.key];
            setExpandedKeys(newExpandedKeys);
        }
    };

    const formatPath = (path: string) => {
        return path.replace(/\/+/g, "/");
    };

    // 初始加载
    useEffect(() => {
        const initTreeData = async () => {
            const rootNodes = await fetchData();
            setTreeData(rootNodes);
        };
        initTreeData();
    }, []);

    const submit = async () => {
        await postCheckChooseFile(
            {
                file_path: currentPath,
            },
            '1',
            navigate,
        ).then(res => {
            if (res.status_code === 'CHOOSE_FILE_OK') {
                choosePath(currentPath)
                changeShow(false)
            }
        }).catch(err => {
            message.error(err.message)
        });
    };

    return (
        <>
            <div className="file-explorer-container">
                <div
                    className="path-display"
                    style={{
                        marginBottom: "20px",
                    }}
                >
                    {/* <Input
                        value={formatPath(currentPath)}
                        readOnly
                        className="path-input"
                        prefix={
                            <span style={{ color: "#999" }}>选中文件：</span>
                        }
                    /> */}
                </div>
                <div
                    style={{
                        maxHeight: "calc(100vh - 100px)",
                        marginBottom: "50px",
                    }}
                >
                    <Spin spinning={loading} tip="加载中..." delay={100}>
                        <Tree
                            loadData={async ({ key, children }) => {
                                if (children || loadedKeys.has(key as string))
                                    return;
                                const childNodes = await fetchData(
                                    key as string,
                                );
                                setTreeData((prev) =>
                                    updateTreeData(
                                        prev,
                                        key as string,
                                        childNodes,
                                    ),
                                );
                                setLoadedKeys((prev) =>
                                    new Set(prev).add(key as string),
                                );
                            }}
                            treeData={treeData}
                            selectedKeys={selectedKeys}
                            expandedKeys={expandedKeys}
                            onSelect={(_, { node }) =>
                                handleNodeInteraction(node)
                            }
                            onExpand={setExpandedKeys}
                            selectable
                            multiple={false}
                            titleRender={(node) => (
                                <div
                                    onClick={() => handleNodeInteraction(node)}
                                    className="tree-node-wrapper"
                                >
                                    {typeof node.title === "function"
                                        ? node.title(node)
                                        : node.title}
                                </div>
                            )}
                            className="custom-tree"
                            blockNode
                        />
                    </Spin>
                </div>
            </div>
            <Space
                style={{
                    position: "absolute",
                    bottom: "10px",
                    right: "10px",
                }}
            >
                <Button
                    onClick={() => {
                        if (changeShow) {
                            changeShow(false);
                        }
                    }}
                >
                    取消
                </Button>
                <Button type={"primary"} onClick={submit}>确认</Button>
            </Space>
        </>
    );
};

export default Wfs;
